from django import forms
from web import models
from web.forms.bootstrap import BootStrapForm
from django.core.exceptions import ValidationError
from web.forms.widgets import ColorRadisSelect


class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['p_color']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    # 重写插件的几种方法
    # p_scan = forms.CharField(widget=forms.Textarea)

    class Meta:
        model = models.Project
        fields = ['p_name', 'p_color', 'p_scan']

        widgets = {
            # 'p_scan':forms.Textarea(attrs={'xx': 123})
            'p_color': ColorRadisSelect(attrs={'class': 'color-radio'})
        }

    def clean_p_name(self):
        """项目校验"""
        name = self.cleaned_data['p_name']
        # 判断项目名是否存在，是否创建过项目
        exists = models.Project.objects.filter(p_name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError("项目名已存在")
        # 项目数是否超过限制
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.p_number:
            raise ValidationError("项目个数已超限,请购买套餐")
        return name
